<?php

namespace App\Http\Controllers\Foundation;


use App\Model\Business\Appointment;
use App\Model\Business\Classe;
use App\Model\Business\Schedule;
use App\Model\Business\ScheduleStuden;
use App\Model\Foundation\Student;
use App\Model\Foundation\Task;
use App\Model\Foundation\TaskReply;
use App\Model\Marketing\Order;
use App\Model\Marketing\Product;
use App\Model\System\Notice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Laravel\Lumen\Routing\Controller as BaseController;
use App\Http\Controllers\MessagePacket;


class TaskController extends BaseController
{
    use MessagePacket;


    /**
     * 获取教师的班级列表
     * @param Request $request
     * @param $id
     * @throws
     * @return array
     */
    function getTeacherClasse(Request $request, $id)
    {
        try{
            $objs = Schedule::select('type', 'classeid')
                ->whereNotNull('classeid')
                ->where('teacheruid', $id)
                ->groupby('type', 'classeid')
                ->get()->toArray();
            $items = [];
            foreach ($objs as $obj){
                $item = [];
                $item['product'] = '';
                $item['type'] = $obj['type'];
                $item['classeid'] = $obj['classeid'];
                if($obj['type']==Schedule::LESSON){
                    $classe = Classe::find($obj['classeid']);
                    $item['classe'] = $classe->classname;
                    if($classe->courseuid){
                      $product = Product::find($classe->courseuid);
                      $item['product'] = $product->title;
                    }
                }else{
                    $classe = Appointment::find($obj['classeid']);
                    $item['classe'] = $classe->coursename;
                    if($classe->orderid){
                        $order = Order::find($classe->orderid);
                        $product = Product::find($order->productid);
                        $item['product'] = $product->title;
                    }
                }
                $items[] = $item;
            }
            return $this->success($items);
        }catch (\Exception $e){
            throw  $e;
            return $this->fail(false, $e->getMessage());
        }
    }


    /**
     * 获取教师所教班级的课节列表
     * @param Request $request
     * @param $tid 教师id
     * @throws
     * @return array
     */
    function getClasseSchedules(Request $request, $tid)
    {
        try{

            if(!$request->has('type')){
                throw new \Exception('need class type');
            }
            if(!$request->has('classeid')){
                throw new \Exception('need class id ');
            }
            $objs = DB::table('schedules')
                            ->select(DB::raw("schedules.*, tasks.id as taskid, tasks.published"))
                            ->where('schedules.teacheruid', $tid)
                            ->where('schedules.type', $request->get('type'))
                            ->where('schedules.classeid', $request->get('classeid'))
                            ->leftjoin('tasks', function ($join){
                                $join->On('schedules.type', '=', 'tasks.classetype')
                                     ->On('schedules.classeid', '=', 'tasks.classeid')
                                     ->On('schedules.scheduleid', '=', 'tasks.scheduleid');
                            })
                            ->get();
            $items = [];
            foreach ($objs as $obj){
                $item = [];
                $item['scheduleid'] = $obj->scheduleid;
                $item['schedulename'] = $obj->name;
                $item['taskid'] = $obj->taskid;
                $item['begintime'] = $obj->begintime;
                $item['students'] = ScheduleStuden::where('scheduleid', $obj->scheduleid)->count();
                $item['replys'] = TaskReply::where('scheduleid', $obj->scheduleid)->where('type',1)->where('status',1)->count();
                if(!$obj->taskid){
                    $item['status'] = 1; # 未创建作业
                }else{
                    if($obj->published){
                        $item['status'] = 3; #以发布，可批改
                    }else{
                        $item['status'] = 2; #未发布
                    }
                }
                $items[] = $item;
            }
            return $this->success($items);
        }catch (\Exception $e){
            throw  $e;
            return $this->fail(false, $e->getMessage());
        }
    }


    /**
     * 获取作业汇总状态信息
     * @param Request $request
     * @param $id
     * @return array
     */
    function getTaskStatus(Request $request, $id)
    {
        try{
            $infos = [];
            $task = Task::find($id);
            $schedule = Schedule::find($task->scheduleid);
            $infos['schedule'] = $schedule->name;
            $infos['students'] = ScheduleStuden::where('scheduleid', $task->scheduleid)->count();
            $infos['replys'] = TaskReply::where('scheduleid', $task->scheduleid)->where('type',1)->where('status',1)->count();
            $infos['unreplys'] = $infos['students'] -$infos['replys'];
            $infos['persent'] = round(($infos['replys']/$infos['students']),2)*100;
            return $this->success($infos);
        }catch (\Exception $e) {
            $this->fail(false, $e->getMessage());
        }
    }

    /**
     * 获取作业学生提交列表
     */
    function getTaskReplys(Request $request, $id)
    {
        try{
            $items = [];
            $task = Task::find($id);
            $objs = DB::table('schedules_students as relation')
                    ->select('students.name','students.studentuid','reply.id','reply.taskid', 'reply.replyat','reply.status')
                    ->where('relation.scheduleid', $task->scheduleid)
                    ->leftjoin('students', "relation.studentuid", 'students.studentuid')
                    ->leftjoin('tasks_replys as reply',function ($join)use($id){
                        $join->on('reply.studentuid', '=', 'relation.studentuid')
                             ->where('reply.type', '=', '1')
                             ->where('reply.taskid', $id)
                             ->where('reply.status', '=', '1');
                    })->get();
            foreach ($objs as $obj){
                $item = [];
                $item['replyid'] = $obj->id;
                $item['student'] = $obj->name;
                $item['taskid'] = $obj->taskid;
                $item['studentuid'] = $obj->studentuid;
                $item['replyed'] = $obj->status;
                $item['replyat'] = $obj->replyat;
                $items[] = $item;
            }
            return $this->success($items);
        }catch (\Exception $e) {
            $this->fail(false, $e->getMessage());
        }
    }


    /**
     * 创建
     * @param Request $request
     * @return array
     */
    function create(Request $request)
    {
        try{
            $data = true;
            $obj = new Task($request->all());
            $obj->addtime = time();
            $obj->save();
            # 一起发布
            if($obj->published==Task::PUBLISHED){
                $this->doPublis($obj);
            }
            return $this->success($data);
        }catch (\Exception $e){
            return $this->fail(false, $e->getMessage());
        }
    }


    /**
     * 更新
     * @param Request $request
     * @param $id
     * @return array
     */
    function update(Request $request, $id)
    {
        try{
            $data = true;
            $obj = Task::find($id);
            $obj->update($request->all());
            $obj->save();
            # 一起发布
            if($obj->published==Task::PUBLISHED){
                $this->doPublis($obj);
            }
            return $this->success($data);
        }catch (\Exception $e){
            return $this->fail(false, $e->getMessage());
        }
    }


    /**
     * 获取单条
     * @param Request $request
     * @param $id
     * @return array
     */
    function get(Request $request, $id)
    {
        try{
            $obj = Task::find($id);
            return $this->success($obj);
        }catch (\Exception $e){
            return $this->fail(false, $e->getMessage());
        }
    }


    /**
     * 批量获取
     * @param Request $request
     * @throws
     * @return array
     */
    function gets(Request $request)
    {
        try{
            if(!$request->has('teacheruid')){
                throw new \Exception('缺少教师Id');
            }
            $tuid = $request->get('teacheruid');
            $query = Task::where('teacheruid', $tuid);
            if($request->has('classeid')){
                $query->where('classeid', $request->get('classeid'));
            }
            if($request->has('scheduleid')){
                $query->where('scheduleid', $request->get('scheduleid'));
            }
            if($request->has('published')){
                $query->where('published', $request->get('published'));
            }
            $data =$query->get();
            return $this->success($data);
        }catch (\Exception $e){
            return $this->fail(false, $e->getMessage());
        }
    }


    /**
     * 发布
     * @param Request $request
     * @param $id
     * @return array
     */
    function publish(Request $request, $id)
    {
        try{
            $data = true;
            $obj = Task::find($id);
            # do pub
            $this->doPublis($obj);
            # 修改状态
            $obj->published = Task::PUBLISHED;
            $obj->pubtime = time();
            $obj->save();
            return $this->success($data);
        }catch (\Exception $e){
            return $this->fail(false, $e->getMessage());
        }
    }


    /**
     * 执行发布动作
     * @param Task $obj
     */
    protected function doPublis(Task $obj)
    {
        # 发布给所有学生
        $studentuids = ScheduleStuden::where('scheduleid', $obj->scheduleid)->pluck('studentuid')->toarray();
        $info = ['taskid'=>$obj->id, 'scheduleid'=>$obj->scheduleid, 'type'=>TaskReply::TASK];
        foreach ($studentuids as $stid){
            $info['studentuid'] = $stid;
            $item = new TaskReply($info);
            $item->save();
        }

        # 给所有学生发送提醒
        $schedule = Schedule::find($obj->scheduleid);

        $msg = ['jsonable'=>'2', 'to'=>'','title'=>'作业发布提醒','body'=>""];



        $users = Student::whereIn('studentuid', $studentuids)->get();
        foreach ($users as $user){
            $body = [
                'title'=> $user->name.'：您好，您有新的作业已发布，请登录系统查看',
                'time'=> $schedule->begintime,
                'coursename'=> $schedule->name,
                'task_title'=>  $obj->title,
                'task_detail'=> '点击进入个人中心查看作业详情',
                'remark'=>'请按时完成作业并在个人中心提交。',
            ];

            $msg['body'] = json_encode($body,JSON_UNESCAPED_UNICODE);
            $msg['to'] = $user->userid;
            $notice = new Notice($msg);
            $notice->save();
        }
    }


}
